/*
 * Copyright 2020-current the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yuehuanghun.mybatis.milu.generic.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

import org.apache.ibatis.cache.Cache;

import com.github.pagehelper.PageHelper;
import com.yuehuanghun.mybatis.milu.criteria.Join;
import com.yuehuanghun.mybatis.milu.criteria.Limit;
import com.yuehuanghun.mybatis.milu.criteria.LimitOffset;
import com.yuehuanghun.mybatis.milu.criteria.Predicate;
import com.yuehuanghun.mybatis.milu.criteria.QueryPredicate;
import com.yuehuanghun.mybatis.milu.criteria.QueryPredicateImpl;
import com.yuehuanghun.mybatis.milu.criteria.builder.QuerySqlTemplateBuilder;
import com.yuehuanghun.mybatis.milu.criteria.builder.QuerySqlTemplateBuilder.BuildResult;
import com.yuehuanghun.mybatis.milu.data.SqlBuildingHelper;
import com.yuehuanghun.mybatis.milu.generic.GenericProviderContext;
import com.yuehuanghun.mybatis.milu.generic.GenericProviderSql;
import com.yuehuanghun.mybatis.milu.mapping.ResultMapHelper;
import com.yuehuanghun.mybatis.milu.pagehelper.Pageable;
import com.yuehuanghun.mybatis.milu.tool.Constants;
import com.yuehuanghun.mybatis.milu.tool.cache.SynchronizedLruCache;

public class GenericFindByCriteriaProviderSql implements GenericProviderSql {

	private final Map<Class<?>, Cache> cache = new ConcurrentHashMap<>();
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public String provideSql(GenericProviderContext context, Object params) {
		Map paramMap = ((Map)params);
		Object criteria = paramMap.remove(Constants.CRITERIA);
		QueryPredicate predicate;
		
		if(Consumer.class.isInstance(criteria)) {
			predicate = new QueryPredicateImpl();			
			((Consumer<Predicate>)criteria).accept(predicate);
		} else {
			predicate = (QueryPredicate) criteria;
		}
		predicate.end();

		if(paramMap.containsKey(Constants.RESULT_TYPE)) { //动态resultType
			ResultMapHelper.setResultType((Class<?>) paramMap.remove(Constants.RESULT_TYPE));
		}
		
		Map<String, Object> queryParams = new HashMap<>();
		int paramIndex = predicate.renderParams(context, queryParams, 0);
		
		for(Join join : ((QueryPredicateImpl)predicate).getJoinModeMap().values()) {
			if(join.getJoinPredicate() != null) {
				paramIndex = join.getJoinPredicate().renderParams(context, queryParams, paramIndex);
			}
		}
		
		 // 处理主动使用PageHelper发起分页设置的，转换排序中的属性为列名
		SqlBuildingHelper.convertLocalPageOrder(context.getEntity(), context.getConfiguration());
		
		if(queryParams.containsKey(Constants.PAGE_KEY)) {
			Limit limit = (Limit)queryParams.remove(Constants.PAGE_KEY);
			if(limit instanceof Pageable) {
				Pageable page = (Pageable)limit;
				PageHelper.startPage(page.getPageNum(), page.getPageSize(), page.isCount());
			} else if(limit instanceof LimitOffset) {
				LimitOffset limitOffset = (LimitOffset)limit;
				PageHelper.offsetPage(limitOffset.getOffset(), limitOffset.getSize(), limitOffset.isCount());
			}
		}
		
		paramMap.putAll(queryParams);
		
		Cache buildResultCache = cache.computeIfAbsent(context.getMapperType(), (clazz) -> {
			return new SynchronizedLruCache(getMethodName()); // 使用LRU缓存，最多存储1024个缓存数据
		});
		
		BuildResult result = (BuildResult)buildResultCache.getObject(predicate);

		if(result == null) {
			result = new QuerySqlTemplateBuilder(context, predicate, 0).build();
			buildResultCache.putObject(predicate, result);
		}
		
		if(!result.getResultMappings().isEmpty()) {
			ResultMapHelper.setResultMappingList(result.getResultMappings());
		}
		
		return result.getSqlTemplate();
	}

	@Override
	public String getMethodName() {
		return "findByCriteria";
	}

}
